<template>
  <div class="abnormal_batch_list">
    <div class="btn_panel">
      <mes-search-comp
        ref="mesSearch2"
        :code-scan="true"
        code-placeholder="[周转码]"
        :searchList="searchList"
        :searchResult="searchResult"
        :searchSeniorShow="true"
        :searchSeniorBtnShow="false"
        :showSlotExport="true"
        v-bind="$attrs"
        @searchInfo="_info"
        @codeSubmit="handleCodeScan"
        @exportTable="_exportTable">
      </mes-search-comp>
    </div>
    <div class="table_container">
      <el-table
        ref="tableNode"
        :data="listData.list"
        border
        stripe
        style="width: 100%"
        :max-height="tableCascadeHeight"
        @sort-change="_sort"
        :row-class-name="({row}) => !selectData.some((item) => item.id === row.id) || 'line_selected'"
        @row-click="(row) => $refs.tableNode.toggleRowSelection(row)"
        @selection-change="handleSelectionChange"
        @filter-change="handleFilterChange"
        v-loading="isLoading">
        <el-table-column
          fixed="left"
          align="center"
          type="selection"
          width="40">
        </el-table-column>
        <mes-col-comp
          :key="index"
          v-for="(column, index) in columnList"
          :column="column">
        </mes-col-comp>
        <el-table-column
          fixed="right"
          :resizable="false"
          prop="id"
          label="操作"
          align="center"
          class-name="operation_btn"
          min-width="160"
          show-overflow-tooltip>
          <template slot-scope="scope">
            <span class="jump_item" @click.stop="wakeBatch(scope.row)">生产调度</span>
            <span class="jump_item" @click.stop="showLog(scope.row)">操作记录</span>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <mes-pagination
      @updateData="init"
      :currentPage="listData.pageNo"
      :total="listData.count || 0"
      :pageSize="listData.pageSize">
    </mes-pagination>
    <!--生产调度-->
    <dispatch-list ref="DispatchList" :intoData="insertData" @submitSuccess="init"></dispatch-list>
    <!--下发要料-->
    <material-demand ref="MaterialDemand" @sendSuccess="init"></material-demand>
    <!-- 日志详情 -->
    <log-detail ref="logDetail"></log-detail>
  </div>
</template>

<script>
import DispatchList from './DispatchList'
import MaterialDemand from './MaterialDemand'
import computed from './anormalTurnoverBatchCol'

export default {
  name: 'AbnormalBatchList',
  props: {
    ids: String
  },
  components: {
    DispatchList,
    MaterialDemand,
  },
  data() {
    return {
      isLoading: false, // 是否加载
      showStatus: false, // 组件是否显示
      searchData: {}, // 搜索列表数据
      sortData: {}, // 排序字段
      insertData: {}, // 调度组件数据导入
      searchResult: NaN, // 搜索结果数
      selectData: [], // 清单选择列表
      listData: [], // 清单列表数据
      abNormalNum: 0, // 非正常任务数量
      workorderIds: '', // 工单ID
      currentIds: '', // 当前请求的工单id
      codeValue: '', // 扫码数值
      workeroderMsg: null, // 任务号、工单号
    }
  },
  computed: computed,
  mounted() {
    this.workorderIds = this.ids
    this.init()
  },
  methods: {
    // 列筛选回调
    handleFilterChange(filters) {
      this.sortData = {}
      this.$refs.tableNode.clearSort()
      let filterParams = this.$filterParams(this.searchList, filters)
      Object.assign(this.searchData, filterParams.search)
      Object.assign(this.sortData, filterParams.order)
      this.init()
    },
    // 扫码
    handleCodeScan(value) {
      this.$refs.mesSearch2.clean()
      this.codeValue = value
      this.init()
    },
    // 导出表格
    _exportTable() {
      let postData = this.getPostData({
        pageNo: 1,
        pageSize: 9999999
      }, [])
      this.$exportTable(postData, 'a/turnoverbatch/turnoverBatch/exportasexcel', '待处理异常任务')
    },
    /**
     * 刷新数据
     * @param ids 工单id
     * @param isClean 是否清空搜索条件
     *  @param workeroderMsg 任务号、工单号
     */
    refresh(ids, isClean, workeroderMsg) {
      this.$refs.tableNode.clearSort()
      this.$refs.tableNode.clearFilter()
      this.sortData = {}
      this.workorderIds = ids || (Array.isArray(workeroderMsg) ? workeroderMsg.join(',') : '')
      if (!Array.isArray(workeroderMsg) && workeroderMsg) {
        this.workeroderMsg = {taskNumber: workeroderMsg || undefined}
      } else {
        this.workeroderMsg = {taskNumber: undefined}
      }
      if (isClean) {
        this.searchData = {}
        this.$refs.mesSearch2.clean()
      }
      if (!this.isLoading) this.init()
    },
    // 获取请求数据
    getPostData(page, fields) {
      let postData = {
        pageNo: page ? page.pageNo : 1,
        pageSize: page ? page.pageSize : this.listData.pageSize || 15,
        sort: this.sortData,
        query: {columns: this.columnList.reduce((pre, cur) => [...pre, cur.prop], fields),
          ...this.searchData,
          viewSource: 3,
          ...this.workeroderMsg
        }
      }
      if (this.workorderIds) {
        postData.query.workorderId = this.workorderIds
        this.currentIds = this.workorderIds
      } else {
        this.currentIds = ''
      }
      if (Object.keys(this.searchData).length > 0) {
        if (!postData.query.taskTypeId) {
          postData.query.taskTypeId = this.abNormalTaskTypeId
        }
        if (!postData.query.turnoverProcessStatusId) {
          postData.query.turnoverProcessStatusId = this.partBatchProcessId
        }
      } else {
        postData.query.taskTypeId = this.abNormalTaskTypeId
        postData.query.turnoverProcessStatusId = this.partBatchProcessId
      }
      if (this.codeValue) {
        postData.query.number = this.codeValue
      }
      return postData
    },
    /**
     * 列表数据请求
     * @param page
     */
    init(page) {
      this.isLoading = true
      const fields = ['workorderId', 'workorderNumber']
      let postData = this.getPostData(page, fields)
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverbatch/turnoverBatch/list',
        data: postData,
        noCommit: true
      }).then((data) => {
        let res = data.data
        this.listData = res
        if (Object.keys(this.searchData).length > 0) {
          this.searchResult = res.count
        } else {
          this.searchResult = NaN
        }
        this.$emit('abNormalList', res.count)
      }).finally(() => {
        if (this.currentIds !== this.workorderIds) {
          this.init()
        }
        this.isLoading = false
      })
    },
    // 条件查询
    _info(data) {
      this.$refs.tableNode.clearSort()
      this.$refs.tableNode.clearFilter()
      this.sortData = {}
      this.searchData = data
      this.init()
    },
    // 排序
    _sort(obj) {
      this.sortData = this.$getSortOrder(obj)
      this.init()
    },
    /**
     * 选择表格
     * @param val
     */
    handleSelectionChange(val) {
      this.selectData = val
      this.$emit('abnormalSelectBatch', this.selectData)
    },
    /**
     * 变更批次状态请求数据收集
     * @param targetStatusId 批次需要变成的状态Id
     */
    statusCollect(targetStatusId) {
      return {
        ids: this.selectData.map((item) => item.id),
        actionId: targetStatusId
      }
    },
    // 下发周转批次
    sendBatch(value) {
      if (this.isLoading) return
      this.changeBatch('Issue', '下发')
    },
    // 下发周转批次
    changeBatch(value, str) {
      let statusId = this.batchActionType.find(item => item.value === value).id
      let postData = this.statusCollect(statusId)
      this.confirmOpen('选中的任务状态将被' + str + ', 是否继续?', str + '提示').then(() => {
        this.changeStatus(postData)
      })
    },
    /**
     * 暂停、恢复、分级终止,变更状态请求
     * @param postData 状态变更请求对象
     */
    changeStatus(postData) {
      this.$store.dispatch('saveData', {
        method: 'post',
        url: 'a/turnoverbatch/turnoverBatch/changestatus',
        data: postData,
        module: 'workSheetManage',
        state: 'changeStatus'
      }).then(() => {
        this.tipMessage('success', '下发成功')
        this.init()
      })
    },
    /**
     * 开启调度组件
     * @param value 当前批次信息数据
     * 只有在待下发、已下发、生产中状态才能开启调度组件
     */
    wakeBatch(value) {
      this.insertData = {
        dateRange: {
          planStartDate: value.planStartDate,
          planEndDate: value.planEndDate
        }
      }
      this.$refs.DispatchList.openDialog(value.workorderId, value.id, value.turnoverProcessStatusValue)
    },
    // 日志
    showLog(row) {
      this.$refs.logDetail.openDialog({
        title: '周转码',
        name: row.number,
        url: 'a/turnoverstatuschangehistory/turnoverStatusChangeHistory/list',
        query: {
          turnoverBatchId: row.id
        }
      })
    },
    /**
     * 提示
     * @param str 提示内容
     */
    tipMessage(type, str) {
      this.$message({
        type: type,
        message: str,
        duration: 1500,
        center: true
      })
    }
  }
}
</script>

<style lang="less">
  .abnormal_batch_list{
    .mes_search{
      width: 100%;
      .search_ordinary{
        padding-right: 0;
        margin-right: 0;
      }
    }
  }
  .batch_list{
    padding: 10px 0 20px 0;
    margin: 0 20px 0 20px;
  }
  .btn_title{
    padding-left: 20px;
  }
  .btn_panel{
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding:0;
    font-size: 14px;
  }
  .normal_panel{
    color:@mesFontWhite!important;
    i{
      color:@mesFontWhite!important;
    }
  }
  .el-table .cell{
    .btn_cell{
      cursor:pointer;
      color: @mesAvailableBtnC;
      i{
        padding-right: 4px;
      }
      &.active{
        color: @mesAvailableBtnC;
      }
      &.end{
        color: @mesDisvailableBtnC!important;
        cursor:not-allowed!important;
      }
    }
  }
</style>
